{% extends "base.html" %}

{% block title %}我的预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}我的预约{% endblock %}

{% block extra_css %}
<style>
    .stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        text-align: center;
    }

    .stats-number {
        font-size: 2rem;
        font-weight: bold;
        margin: 10px 0 5px 0;
    }

    .stats-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }

    .reservation-card {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 15px;
        background: white;
        transition: all 0.2s ease;
        position: relative;
    }

    .reservation-card:hover {
        border-color: #007bff;
        box-shadow: 0 4px 12px rgba(0,123,255,0.1);
    }

    .reservation-status {
        position: absolute;
        top: 15px;
        right: 15px;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }

    .status-pending {
        background: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
    }

    .status-confirmed {
        background: #d1edff;
        color: #0c5460;
        border: 1px solid #b8daff;
    }

    .status-cancelled {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .status-completed {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .status-no_show {
        background: #e2e3e5;
        color: #383d41;
        border: 1px solid #d6d8db;
    }

    .reservation-time {
        font-size: 1.1rem;
        font-weight: 600;
        color: #007bff;
        margin-bottom: 10px;
    }

    .reservation-details {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .reservation-actions {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #e9ecef;
    }

    .filter-card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .quick-actions {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .btn-action {
        margin-right: 5px;
        margin-bottom: 5px;
    }

    .upcoming-indicator {
        background: linear-gradient(45deg, #ff6b6b, #ee5a52);
        color: white;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 11px;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.7; }
        100% { opacity: 1; }
    }

    .time-warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 6px;
        padding: 8px 12px;
        margin-top: 10px;
        font-size: 0.85rem;
        color: #856404;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        color: #dee2e6;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-number">{{ statistics.total_reservations or 0 }}</div>
                <div class="stats-label">总预约数</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                <div class="stats-number">{{ statistics.completed_reservations or 0 }}</div>
                <div class="stats-label">已完成</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333;">
                <div class="stats-number">{{ statistics.upcoming_reservations or 0 }}</div>
                <div class="stats-label">即将开始</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #333;">
                <div class="stats-number">{{ statistics.completion_rate or 0 }}%</div>
                <div class="stats-label">完成率</div>
            </div>
        </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">预约管理</h5>
                <small class="text-muted">管理您的课程预约</small>
            </div>
            <div class="col-md-6 text-end">
                <a href="{{ url_for('student_reservations.create') }}" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 新建预约
                </a>
                <a href="{{ url_for('student_reservations.calendar') }}" class="btn btn-outline-primary">
                    <i class="bi bi-calendar3"></i> 日历视图
                </a>
            </div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-card">
        <form method="GET" action="{{ url_for('student_reservations.index') }}">
            <div class="row g-3">
                <div class="col-md-2">
                    <label class="form-label">状态</label>
                    {{ filter_form.status(class="form-select") }}
                </div>
                <div class="col-md-3">
                    <label class="form-label">开始日期</label>
                    {{ filter_form.start_date(class="form-control") }}
                </div>
                <div class="col-md-3">
                    <label class="form-label">结束日期</label>
                    {{ filter_form.end_date(class="form-control") }}
                </div>
                <div class="col-md-3">
                    <label class="form-label">教练</label>
                    {{ filter_form.coach_id(class="form-select") }}
                </div>
                <div class="col-md-1">
                    <label class="form-label">&nbsp;</label>
                    <div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i>
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 预约列表 -->
    <div class="row">
        {% if reservations %}
            {% for reservation in reservations %}
            <div class="col-12">
                <div class="reservation-card">
                    <!-- 状态标签 -->
                    <div class="reservation-status status-{{ reservation.status }}">
                        {{ reservation.get_status_display() }}
                        {% if reservation.is_upcoming() %}
                            <span class="upcoming-indicator ms-1">即将开始</span>
                        {% endif %}
                    </div>

                    <div class="row">
                        <div class="col-md-3">
                            <div class="reservation-time">
                                <i class="bi bi-calendar3"></i>
                                {{ reservation.reservation_date.strftime('%m月%d日') }}
                                <br>
                                <small>{{ reservation.reservation_date.strftime('%A') }}</small>
                            </div>
                            <div class="reservation-details">
                                <i class="bi bi-clock"></i>
                                {{ reservation.start_time.strftime('%H:%M') }} -
                                {{ reservation.end_time.strftime('%H:%M') }}
                                <br>
                                <small>{{ reservation.duration_minutes }}分钟</small>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div><strong>教练</strong></div>
                            <div class="reservation-details">
                                <i class="bi bi-person-check"></i>
                                {{ reservation.coach.real_name }}
                                <br>
                                <small>{{ reservation.coach.level or '教练' }}</small>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div><strong>球台信息</strong></div>
                            <div class="reservation-details">
                                <i class="bi bi-grid-3x3"></i>
                                {{ reservation.table.name }}
                                <br>
                                <small>{{ reservation.table.description or '标准球台' }}</small>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div><strong>费用</strong></div>
                            <div class="reservation-details">
                                <i class="bi bi-currency-dollar"></i>
                                ¥{{ "%.2f"|format(reservation.get_price_yuan()) }}
                                {% if reservation.status == 'cancelled' and reservation.cancel_reason %}
                                    <br>
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle"></i>
                                        {{ reservation.cancel_reason }}
                                    </small>
                                {% endif %}
                            </div>
                        </div>
                    </div>

                    <!-- 时间提醒 -->
                    {% if reservation.status == 'confirmed' and reservation.is_upcoming() %}
                    <div class="time-warning">
                        <i class="bi bi-clock-history"></i>
                        预约即将开始，请提前到达球台！
                    </div>
                    {% elif reservation.status in ['pending', 'confirmed'] and not reservation.can_be_cancelled() %}
                    <div class="time-warning">
                        <i class="bi bi-exclamation-triangle"></i>
                        预约开始前24小时内无法修改或取消
                    </div>
                    {% endif %}

                    <!-- 操作按钮 -->
                    <div class="reservation-actions">
                        <a href="{{ url_for('student_reservations.detail', reservation_id=reservation.id) }}"
                           class="btn btn-sm btn-outline-primary btn-action">
                            <i class="bi bi-eye"></i> 查看详情
                        </a>

                        {% if reservation.status == 'pending' and reservation.can_be_cancelled() %}
                        <a href="{{ url_for('student_reservations.edit', reservation_id=reservation.id) }}"
                           class="btn btn-sm btn-outline-warning btn-action">
                            <i class="bi bi-pencil"></i> 修改预约
                        </a>
                        {% endif %}

                        {% if reservation.can_be_cancelled() %}
                        <button type="button" class="btn btn-sm btn-outline-danger btn-action"
                                onclick="quickCancel({{ reservation.id }}, '{{ reservation.coach.real_name }}', '{{ reservation.reservation_date.strftime('%m月%d日') }}')">
                            <i class="bi bi-x-circle"></i> 取消预约
                        </button>
                        {% endif %}

                        {% if reservation.status == 'completed' %}
                        <a href="{{ url_for('evaluations.create', reservation_id=reservation.id) }}"
                           class="btn btn-sm btn-outline-success btn-action">
                            <i class="bi bi-star"></i> 评价课程
                        </a>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}

            <!-- 分页导航 -->
            {% if pagination and pagination.pages > 1 %}
            <div class="col-12">
                <nav aria-label="分页导航" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if pagination.has_prev %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('student_reservations.index', page=pagination.prev_num, **filter_params) }}">
                                上一页
                            </a>
                        </li>
                        {% endif %}

                        {% for page_num in pagination.iter_pages() %}
                            {% if page_num %}
                                {% if page_num != pagination.page %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('student_reservations.index', page=page_num, **filter_params) }}">
                                        {{ page_num }}
                                    </a>
                                </li>
                                {% else %}
                                <li class="page-item active">
                                    <span class="page-link">{{ page_num }}</span>
                                </li>
                                {% endif %}
                            {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                            {% endif %}
                        {% endfor %}

                        {% if pagination.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('student_reservations.index', page=pagination.next_num, **filter_params) }}">
                                下一页
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                    <div class="text-center text-muted mt-2">
                        显示第 {{ pagination.per_page * (pagination.page - 1) + 1 }} -
                        {{ pagination.per_page * pagination.page if pagination.page < pagination.pages else pagination.total }} 条，
                        共 {{ pagination.total }} 条记录
                    </div>
                </nav>
            </div>
            {% endif %}

        {% else %}
            <div class="col-12">
                <div class="empty-state">
                    <i class="bi bi-calendar-x"></i>
                    <h5>暂无预约记录</h5>
                    <p class="text-muted">您还没有任何预约记录，快去预约您的第一节课程吧！</p>
                    <a href="{{ url_for('student_reservations.create') }}" class="btn btn-primary">
                        <i class="bi bi-plus-circle"></i> 创建预约
                    </a>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<!-- 快速取消预约模态框 -->
<div class="modal fade" id="quickCancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">取消预约</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i>
                    您确定要取消与 <span id="cancelCoachName" class="fw-bold"></span>
                    在 <span id="cancelDate" class="fw-bold"></span> 的预约吗？
                </div>
                <div class="mb-3">
                    <label class="form-label">取消原因</label>
                    <select id="cancelReason" class="form-select">
                        <option value="个人原因">个人原因</option>
                        <option value="时间冲突">时间冲突</option>
                        <option value="身体不适">身体不适</option>
                        <option value="紧急情况">紧急情况</option>
                        <option value="其他原因">其他原因</option>
                    </select>
                </div>
                <small class="text-muted">
                    <i class="bi bi-info-circle"></i>
                    取消预约可能会影响您的信用记录，请谨慎操作。
                </small>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmQuickCancel()">
                    确认取消预约
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentCancelId = null;

// 快速取消预约
function quickCancel(reservationId, coachName, date) {
    currentCancelId = reservationId;
    document.getElementById('cancelCoachName').textContent = coachName;
    document.getElementById('cancelDate').textContent = date;

    const modal = new bootstrap.Modal(document.getElementById('quickCancelModal'));
    modal.show();
}

// 确认取消预约
function confirmQuickCancel() {
    if (!currentCancelId) return;

    const reason = document.getElementById('cancelReason').value;

    fetch(`/student-reservations/api/reservation/${currentCancelId}/quick-cancel`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        },
        body: JSON.stringify({ reason: reason })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('取消失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
}

// 自动刷新即将开始的预约状态
function refreshUpcomingReservations() {
    const upcomingElements = document.querySelectorAll('.upcoming-indicator');
    if (upcomingElements.length > 0) {
        fetch('/student-reservations/api/upcoming')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新页面中的即将开始标识
                    // 这里可以添加更复杂的更新逻辑
                }
            })
            .catch(error => console.error('刷新失败:', error));
    }
}

// 页面加载完成后设置自动刷新
document.addEventListener('DOMContentLoaded', function() {
    // 每5分钟刷新一次即将开始的预约
    setInterval(refreshUpcomingReservations, 5 * 60 * 1000);

    // 设置日期选择器的默认值
    const today = new Date().toISOString().split('T')[0];
    const startDateInput = document.querySelector('input[name="start_date"]');
    const endDateInput = document.querySelector('input[name="end_date"]');

    if (startDateInput && !startDateInput.value) {
        startDateInput.setAttribute('min', today);
    }

    if (endDateInput && !endDateInput.value) {
        endDateInput.setAttribute('min', today);
    }
});
</script>
{% endblock %}